package gcu.module.owner.rest;

import gcu.module.owner.daomain.Owner;
import gcu.module.owner.service.OwnerService;
import gcu.module.owner.service.UploadService;
import gcu.module.room.daomain.Room;
import gcu.module.room.service.RoomService;
import gcu.util.JsonMapper;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * Created by haol on 2016/9/23.
 */
@RestController
@RequestMapping("/rest/owner")
public class OwnerRestController {
      private Logger logger = LoggerFactory.getLogger(OwnerRestController.class);

      @Autowired
      private OwnerService ownerService;
      @Autowired
      private UploadService uploadService;

      @RequestMapping(value = "/get", method = RequestMethod.GET)
      public Map<String, Object> get(Integer id) {
            return ownerService.get(id);
      }

      @RequestMapping(value = "/save", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
      public boolean save(@RequestBody Owner owner) {
            if (owner.getId() == null){
                  ownerService.add(owner);
            }else {
                  ownerService.update(owner);
            }
            return true;
      }
      @RequestMapping(value = "/checkOwnerIsTrue",method = RequestMethod.POST)
      public boolean check(String applyName){
            Owner owner = ownerService.queryOwnerByName(applyName);
            if (owner == null){
                  return  false;
            }else {
                  return true;
            }
      }
      @RequestMapping(value = "/download", method = RequestMethod.GET)
      public ResponseEntity<byte[]> download() throws Exception {

            File file_ = new File("/usr/file/path.txt");
            Scanner scanner = new Scanner(file_);
            String path_ = scanner.next();
            String path = path_;
            int i = path_.lastIndexOf('/');
            String name = path_.substring(i+1);

           // File file_ = new File("D:\\Village.xls");
            //String path = "D:\\Village.xls";
            //String name = "Village.xls";

            File file = new File(path);
            HttpHeaders headers = new HttpHeaders();
            String fileName = new String(name.getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
      }
      /**
       * 上传文件，使用超哥的工具包
       * @param file
       * @param request
       * @param response
       * @param model
       */
      @RequestMapping(value = "/upload", method = RequestMethod.POST)
      public void upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response, Model model){
            String uploadDir = request.getServletContext().getRealPath("/upload");
            logger.info("上传文件路径为：{}", uploadDir);
            JsonMapper mapper = JsonMapper.nonDefaultMapper();
            PrintWriter out = null;
            try {
                  response.setContentType("text/html; charset=UTF-8");
                  out = response.getWriter();
                  Map<String, Object> result =uploadService.handleFiles(file, uploadDir,model);
                  out.print(mapper.toJson(result));
            } catch (IOException e) {
                  e.printStackTrace();
            } finally {
                  if(out != null) {
                        out.flush();
                        out.close();
                  }
            }
      }
      @RequestMapping(value = "/delByChecked",method = RequestMethod.POST)
      public String delByChecked(String delitems) {
            List<String> delList = new ArrayList<String>();
            String[] strs = delitems.split(",");
            for (String str : strs) {
                  delList.add(str);
            }
            ownerService.delete(delList);
            return "redirect:/owner/list";
      }

}
